#include "head.h"

int net_ls(request_t *request, int net_fd, MYSQL *mysql) {
    // 获取并拼接当前路径
    char full_path[1024] = {0};
    getcwd(full_path, sizeof(full_path));
    strcat(full_path, "/");
    strcat(full_path, request->user_name);
    // strcat(full_path, "/");
    strcat(full_path, request->path);
    // strcat(full_path, "/");
    printf("服务端拼接的完整路径为: %s\n", full_path);

    // 数据库中存储的文件路径是从username/开始的
    // 如.../username/hello在数据库中存储的路径为/hello
    // 从数据库中读取文件当前路径的文件列表

    // 获取相对路径
    char relative_path[100] = {0};
    // strcpy(relative_path, "/");
    strcpy(relative_path, request->path);

    // 从数据库中查询并读取相对路径所在的文件id
    int user_id = get_user_id(request->user_name, mysql);
    char sql[1024] = {0};
    snprintf(sql, sizeof(sql), "select id from files where path = '%s' and user_id = %d", relative_path, user_id);
    int ret = mysql_query(mysql, sql);
    if (ret != 0) {
        printf("select: %s\n", mysql_error(mysql));
    }
    MYSQL_RES *result = mysql_store_result(mysql);
    if (result == NULL) {
        printf("store: %s\n", mysql_error(mysql));
    }
    MYSQL_ROW row;
    if (row = mysql_fetch_row(result)) {
        printf("读取了文件id\n");
        int num = atoi(row[0]);
        memset(sql, 0, sizeof(sql));
        sprintf(sql, "select filename from files where father_id = %d and delete_flag = 1", num);
        int ret = mysql_query(mysql, sql);
        if (ret != 0) {
            printf("select: %s\n", mysql_error(mysql));
            // return -1;
        }
        memset(result, 0, sizeof(MYSQL_RES));
        result = mysql_store_result(mysql);
        if (result == NULL) {
            printf("store: %s\n", mysql_error(mysql));
            // return -1;
        }
        memset(row, 0, sizeof(MYSQL_ROW));
        printf("读取了文件列表\n");
        // 读取文件列表
        char buf[1024] = {0};
        int count = 0;
        while ((row = mysql_fetch_row(result))) {
            for (int i = 0; i < mysql_num_fields(result); ++i) {
                // 输出文件名
                // 按照整齐的格式输出到buf中
                sprintf(buf + strlen(buf), "%-10s", row[i]);
                count++;
                //strcat(buf, "\t");
                // 每打印五个文件名后换行
                if (count == 5) {
                    strcat(buf, "\n");
                    count = 0;
                }
            }
        }
        response_t response;
        response.status = 0;
        strcpy(response.args, buf);
        printf("%s\n", response.args);
        send(net_fd, &response, sizeof(response), 0);
        printf("响应了ls请求\n");
        printf("---\n");
    } else {
        // 发送响应
        // end:
        response_t response;
        response.status = 1;
        strcpy(response.args, "directory is empty");
        send(net_fd, &response, sizeof(response_t), 0);
        printf("响应了ls请求\n");
        printf("---\n");
    }
    mysql_free_result(result);
    return 0;
}
